package com.tth.learn.addproperties.com.tth.learn.java2;

import com.tth.learn.addproperties.java1.Person;
import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @Author tth
 * @Date 2022/12/29 17:20
 */
public class OtherTest {

    /**
     * 获取当前运行时类的构造器
     */
    @Test
    public void test1() {
        Class<Person> clazz = Person.class;
        // getConstructors()：获取当前运行时类中声明为public的构造器，不包含父类构造器
        Constructor<?>[] constructors = clazz.getConstructors();
        for (Constructor c: constructors) {
            System.out.println(c);
        }

        System.out.println("**************");

        // getDeclaredConstructors()：获取当前运行时类中的所有构造器，不包含父类构造器
        Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
        for (Constructor c: declaredConstructors) {
            System.out.println(c);
        }
    }

    /**
     * 获取当前运行时类的父类
     */
    @Test
    public void test2() {
        Class<Person> clazz = Person.class;
        // getSuperclass()：获取当前运行时类的父类
        Class<? super Person> superclass = clazz.getSuperclass();
        System.out.println(superclass);

        // getGenericSuperclass()：获取当前运行时类带泛型的父类
        Type genericSuperclass = clazz.getGenericSuperclass();
        System.out.println(genericSuperclass);
        ParameterizedType paramType = (ParameterizedType) genericSuperclass;
        // 获取泛型类型
        Type[] actualTypeArguments = paramType.getActualTypeArguments();
        for (int i = 0; i < actualTypeArguments.length; i++) {
            if (i == actualTypeArguments.length - 1) {
                System.out.println(actualTypeArguments[i]);
            }else {
                System.out.println(actualTypeArguments[i].getTypeName() + ", ");
            }
        }
    }

    /**
     * 获取当前运行时类实现的接口
     */
    @Test
    public void test3() {
        Class<Person> clazz = Person.class;
        // getInterfaces()：获取当前运行时类的接口
        Class<?>[] interfaces = clazz.getInterfaces();
        for (Class c: interfaces) {
            System.out.println(c);
        }
    }

    /**
     * 获取当前运行时类所在的包
     */
    @Test
    public void test4() {
        Class<Person> clazz = Person.class;
        // getPackage()：获取当前运行时类所在的包
        Package pack = clazz.getPackage();
        System.out.println(pack);
    }

    /**
     * 获取当前运行时类声明的注解
     */
    @Test
    public void test5() {
        Class<Person> clazz = Person.class;
        // getAnnotations()：获取当前运行时类声明的注解
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation anno: annotations) {
            System.out.println(anno);
        }
    }
}
